package org.jeecg.modules.htxincailiao.order.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.SmartBeanUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTMerchant;
import org.jeecg.modules.htxincailiao.account.service.IHTMerchantService;
import org.jeecg.modules.htxincailiao.address.domain.vo.HTAddressVO;
import org.jeecg.modules.htxincailiao.address.service.IHTBuyerAddressService;
import org.jeecg.modules.htxincailiao.area.service.IHTAreaService;
import org.jeecg.modules.htxincailiao.cart.common.HTCartHelper;
import org.jeecg.modules.htxincailiao.cart.entity.HTCart;
import org.jeecg.modules.htxincailiao.cart.service.IHTCartService;
import org.jeecg.modules.htxincailiao.express.entity.HTExpressCategory;
import org.jeecg.modules.htxincailiao.express.service.IHTExpressCategoryService;
import org.jeecg.modules.htxincailiao.goods.entity.HTGoods;
import org.jeecg.modules.htxincailiao.goods.service.IHTGoodsService;
import org.jeecg.modules.htxincailiao.industry.domain.bo.HTIndustryEventBO;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustryExhibition;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustryMeeting;
import org.jeecg.modules.htxincailiao.industry.entity.HTIndustrySalon;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustryExhibitionService;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustryMeetingService;
import org.jeecg.modules.htxincailiao.industry.service.IHTIndustrySalonService;
import org.jeecg.modules.htxincailiao.library.entity.HTLibrary;
import org.jeecg.modules.htxincailiao.library.service.IHTLibraryService;
import org.jeecg.modules.htxincailiao.order.constant.HTOrderInfoTypeEnum;
import org.jeecg.modules.htxincailiao.order.constant.HTOrderTypeEnum;
import org.jeecg.modules.htxincailiao.order.domain.bo.HTIndustryOrderCreateBO;
import org.jeecg.modules.htxincailiao.order.domain.bo.HTOrderIndustryBO;
import org.jeecg.modules.htxincailiao.order.domain.bo.HTOrderInfoBO;
import org.jeecg.modules.htxincailiao.order.domain.bo.HTSubmitOrderBO;
import org.jeecg.modules.htxincailiao.order.domain.vo.*;
import org.jeecg.modules.htxincailiao.order.entity.*;
import org.jeecg.modules.htxincailiao.order.mapper.HTOrderMapper;
import org.jeecg.modules.htxincailiao.order.service.*;
import org.jeecg.modules.htxincailiao.payment.domain.vo.HTPaymentVO;
import org.jeecg.modules.htxincailiao.payment.entity.HTPayment;
import org.jeecg.modules.htxincailiao.payment.service.IHTPaymentService;
import org.jeecg.modules.htxincailiao.report.entity.HTReport;
import org.jeecg.modules.htxincailiao.report.service.IHTReportService;
import org.jeecg.modules.htxincailiao.shop.entity.HTShop;
import org.jeecg.modules.htxincailiao.shop.service.IHTShopService;
import org.jeecg.modules.vendors.tencent.account.entity.HTTencentAccount;
import org.jeecg.modules.vendors.tencent.account.service.IHTTencentAccountService;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static org.jeecg.modules.htxincailiao.order.constant.HTOrderInfoTypeEnum.CONFIRM_FROM_CART;
import static org.jeecg.modules.htxincailiao.order.constant.HTOrderStatusEnum.*;
import static org.jeecg.modules.htxincailiao.order.constant.HTOrderTypeEnum.*;
import static org.jeecg.modules.htxincailiao.payment.constant.HTPaymentStatusEnum.PAID;
import static org.jeecg.modules.htxincailiao.payment.constant.HTPaymentStatusEnum.WAITING_PAYMENT;


/**
 * @Description: ht_order
 * @Author: jeecg-boot
 * @Date: 2021-11-08 16:58:42
 * @Version: V1.0
 */
@Service
public class HTOrderServiceImpl extends ServiceImpl<HTOrderMapper, HTOrder> implements IHTOrderService {

    private static final Logger logger = LoggerFactory.getLogger(HTOrderServiceImpl.class);

    @Resource
    private IHTCartService cartService;

    @Resource
    private IHTShopService shopService;

    @Resource
    private IHTMerchantService ihtMerchantService;

    @Resource
    private IHTGoodsService goodsService;

    @Resource
    private IHTLibraryService libraryService;

    @Resource
    private IHTReportService reportService;

    @Resource
    private IHTOrderShopService orderShopService;

    @Resource
    private IHTOrderGoodsService orderGoodsService;

    @Resource
    private IHTOrderLibraryService orderLibraryService;

    @Resource
    private IHTOrderReportService orderReportService;

    @Resource
    private IHTPaymentService paymentService;

    @Resource
    private IHTOrderMeetingService orderMeetingService;

    @Resource
    private IHTBuyerAddressService buyerAddressService;

    @Resource
    private IHTIndustryMeetingService industryMeetingService;

    @Resource
    private IHTIndustryExhibitionService industryExhibitionService;

    @Resource
    private IHTOrderExhibitionService orderExhibitionService;

    @Resource
    private IHTIndustrySalonService industrySalonService;

    @Resource
    private IHTOrderSalonService orderSalonService;

    @Resource
    private IHTAreaService areaService;

    @Resource
    private IHTExpressCategoryService expressCategoryService;

    @Resource
    private IHTTencentAccountService tencentAccountService;

    /**
     * 通过订单编号查询订单实体
     *
     * @param orderSn
     * @return 返回OrderPay 订单支付表
     */
    public HTOrder queryByOrderSn(String orderSn) {
        return baseMapper.queryByOrderSn(orderSn);
    }

    private HTIndustryEventBO getIndustryEventBOByOrderCreateBO(HTIndustryOrderCreateBO bo) {
        HTIndustryEventBO eventBO = null;
//        System.out.printf("\n\n\n getOrderType %s \n\n\n", JSONObject.toJSONString(bo.getOrderType()));
        switch (bo.getOrderType()) {
            case INDUSTRY_MEETING: {
                HTIndustryMeeting meeting = industryMeetingService.getById(bo.getMeetingId());
                eventBO = SmartBeanUtil.copy(meeting, HTIndustryEventBO.class);
            }
            break;

            case INDUSTRY_EXHIBITION: {
                HTIndustryExhibition exhibition = industryExhibitionService.getById(bo.getExhibitionId());
                eventBO = SmartBeanUtil.copy(exhibition, HTIndustryEventBO.class);
            }
            break;

            case INDUSTRY_SALON: {
                HTIndustrySalon salon = industrySalonService.getById(bo.getSalonId());
                eventBO = SmartBeanUtil.copy(salon, HTIndustryEventBO.class);
            }
            break;

            default:
                break;
        }

        return eventBO;
    }

    /**
     * 提交订单
     * <p>
     * d @param bo
     *
     * @return 返回 submitOrderVO
     */
    @Override
    @Transactional
    public HTSubmitOrderVO createOrderForIndustry(@Valid HTIndustryOrderCreateBO bo) {
        HTSubmitOrderVO submitOrderVO = new HTSubmitOrderVO();
        HTIndustryEventBO eventBO = getIndustryEventBOByOrderCreateBO(bo);
        eventBO.setApplyCost(bo.getApplyCost());

        String buyerId = bo.getBuyerId();
        Integer quantity = bo.getQuantity();
        Integer paymentType = bo.getPaymentType();
        String addressId = "";
        BigDecimal totalAmount = new BigDecimal(eventBO.getApplyCost().doubleValue() * quantity);
        //前后端金额校验
        if (totalAmount.floatValue() != bo.getTotalAmount().floatValue()) {
            throw new JeecgBootException("前后端金额计算金额不一致，支付信息保存失败");
        }
        totalAmount = bo.getTotalAmount();
        BigDecimal totalDiscountAmount = new BigDecimal(0);
        BigDecimal totalPaymentAmount = BigDecimal.valueOf(totalAmount.doubleValue() - totalDiscountAmount.doubleValue());

        HTOrder order = createOrder(bo.getOrderType(), buyerId, addressId, totalAmount, totalDiscountAmount, totalPaymentAmount);
        boolean succeed;
        try {
            succeed = save(order);
            if (oConvertUtils.isNotEmpty(order)) {
                submitOrderVO.setOrdered(true);
            }
        } catch (Exception e) {
            logger.error(e.toString());
            throw new JeecgBootException("创建订单失败");
        }

        if (succeed) {
            //2 创建支付记录
            HTPayment paymentItem = createPayment(order, paymentType, totalPaymentAmount, bo.getName());
            try {
                paymentService.save(paymentItem);
                order.setPaymentId(paymentItem.getId());
                updateById(order);
                if (oConvertUtils.isNotEmpty(paymentItem)) {
                    submitOrderVO.setPayment(paymentItem);
                }

            } catch (Exception e) {
                logger.error(e.toString());
                throw new JeecgBootException("支付信息保存失败");
            }
            saveOrderEventBy(bo, eventBO, order);
        }

        return submitOrderVO;
    }

    //
    private void saveOrderEventBy(@Valid HTIndustryOrderCreateBO bo, @Valid HTIndustryEventBO eventBO, HTOrder order) {
        // 保存订单会议、会展、沙龙信息表（订单信息记录表）
        String provinceName = HTIndustryEventBO.getProvinceName(eventBO, this.areaService);
        String cityName = HTIndustryEventBO.getCityName(eventBO, areaService);
        String districtName = HTIndustryEventBO.getDistrictName(eventBO, areaService);
        String fullAddress = HTIndustryEventBO.buildFullAddressBy(eventBO, provinceName, cityName, districtName);

        HTOrderIndustryBO orderIndustryEventBO = SmartBeanUtil.copy(eventBO, HTOrderIndustryBO.class);
        orderIndustryEventBO.setOrderId(order.getId());
        orderIndustryEventBO.setBuyerId(bo.getBuyerId());
        orderIndustryEventBO.setContactPerson(bo.getContactPerson());
        orderIndustryEventBO.setContactPhoneNumber(bo.getContactPhoneNumber());
        orderIndustryEventBO.setQuantity(bo.getQuantity());
        orderIndustryEventBO.setOrderStatus(WAITING_USER_PAY.getValue());
        orderIndustryEventBO.setFullAddress(fullAddress);
        orderIndustryEventBO.setApplyObjectType(bo.getApplyObjectType());

        switch (bo.getOrderType()) {
            case INDUSTRY_MEETING: {
                orderIndustryEventBO.setMeetingId(bo.getMeetingId());
                HTOrderMeeting orderMeeting = SmartBeanUtil.copy(orderIndustryEventBO, HTOrderMeeting.class);
                try {
                    orderMeetingService.save(orderMeeting);
                } catch (Exception e) {
                    throw new JeecgBootException("会议订单信息保存失败");
                }
            }
            break;

            case INDUSTRY_EXHIBITION: {
                orderIndustryEventBO.setExhibitionId(bo.getExhibitionId());
                HTOrderExhibition orderExhibition = SmartBeanUtil.copy(orderIndustryEventBO, HTOrderExhibition.class);

                try {
                    orderExhibitionService.save(orderExhibition);
                } catch (Exception e) {
                    throw new JeecgBootException("展会订单信息保存失败");
                }
            }
            break;

            case INDUSTRY_SALON: {
                orderIndustryEventBO.setSalonId(bo.getSalonId());
                HTOrderSalon orderSalon = SmartBeanUtil.copy(orderIndustryEventBO, HTOrderSalon.class);

                try {
                    orderSalonService.save(orderSalon);
                } catch (Exception e) {
                    throw new JeecgBootException("沙龙订单信息保存失败");
                }
            }
            break;

            default:
                break;
        }
    }

    /**
     * 提交订单
     *
     * @param bo
     * @return 返回OrderPay 订单支付表
     */
    //TODO 考虑TradeOrder
    @Override
    @Transactional
    public HTSubmitOrderVO submitOrder(@Valid HTSubmitOrderBO bo) {
        HTSubmitOrderVO submitOrderVO = new HTSubmitOrderVO();
        HTPayment paymentItem = null;
        List<HTOrderProductVO> orderProductVOList = getOrderProductVOListForSubmit(bo);

        //0 获取订单信息
        HTOrderVO orderVO = getShopOrderVOAndUpdateOrderProductVO(orderProductVOList);
        HTOrderTypeEnum orderType = bo.getOrderType();
        String buyerId = bo.getBuyerId();
        String addressId = bo.getAddressId();
        BigDecimal totalAmount = orderVO.getTotalAmount();
        BigDecimal totalDiscountAmount = orderVO.getTotalDiscountAmount();
        BigDecimal totalPaymentAmount = orderVO.getTotalPaymentAmount();
        Integer paymentType = bo.getPaymentType();

        // 创建主订单，数据保存至ht_order表
        HTOrder order = createOrder(orderType, buyerId, addressId, totalAmount, totalDiscountAmount, totalPaymentAmount);
        try {
            save(order);
            if (oConvertUtils.isNotEmpty(order)) {
                submitOrderVO.setOrdered(true);
            }

        } catch (Exception e) {
            throw new JeecgBootException("创建订单失败");
        }
        // 如果有金额，会创建一条付款信息，数据保存至ht_payment表
        if (totalAmount.floatValue() > 0) {
            paymentItem = createPayment(order, paymentType, totalPaymentAmount, orderVO.getPaymentDescription());
            try {
                paymentService.save(paymentItem);
                if (oConvertUtils.isNotEmpty(paymentItem)) {
                    submitOrderVO.setPayment(paymentItem);
                }
            } catch (Exception e) {
                throw new JeecgBootException("支付信息保存失败");
            }
        }
        // 将ht_payment表id保存至ht_order表payment_id中
        try {
            if (oConvertUtils.isNotEmpty(paymentItem)) {
                order.setPaymentId(paymentItem.getId());
                updateById(order);
            }
        } catch (Exception e) {
            throw new JeecgBootException("更新订单PaymentId失败");
        }

        //2 保存订单店铺信息（订单店铺表ht_order_shop）
        saveOrderShopItems(bo, order, orderVO);

        //3 保存订单信息（订单产品表ht_order_goods）
        switch (orderType) {
            case GOODS:
            case LIBRARY:
            case REPORT:
                saveOrderProductItems(order, orderProductVOList, bo);
                break;
            default:
                break;
        }

        //4 移除购物车相关Item
        removeCartItemIfNeed(bo, orderProductVOList);

        return submitOrderVO;
    }


    private void handleOrderVOForOrderedGoodsBy(HTOrderVO orderVO, HTOrder order) {
        AtomicReference<String> expressEnterprise = new AtomicReference<>("");
        AtomicReference<String> expressSn = new AtomicReference<>("");
        AtomicReference<String> expressSearchUrl = new AtomicReference<>("");

        HTAddressVO addressVO = buyerAddressService.queryByAddressId(order.getAddressId());
        orderVO.setAddress(addressVO);

        List<HTOrderGoods> orderGoodsList = orderGoodsService.findAllByOrderId(order.getId());
        //按店铺聚合订单商品对象
        Map<String, List<HTOrderGoods>> collect =
                orderGoodsList.stream().collect(Collectors.groupingBy(HTOrderGoods::getShopId));
        collect.forEach((shopId, groupedOrderGoodsList) -> {
            HTOrderShop orderShop = orderShopService.queryByOrderId(order.getId());
            HTOrderShopVO orderShopVO = SmartBeanUtil.copy(orderShop, HTOrderShopVO.class);
            if (oConvertUtils.isNotEmpty(orderShopVO)) {
                if (oConvertUtils.isNotEmpty(groupedOrderGoodsList)) {
                    //按店铺构建订单商品信息项
                    List<HTOrderProductVO> orderProductItems = new ArrayList<>();
                    for (HTOrderGoods orderGoods : groupedOrderGoodsList) {
                        HTOrderProductVO orderProductVO = SmartBeanUtil.copy(orderGoods, HTOrderProductVO.class);
                        if (oConvertUtils.isNotEmpty(orderProductVO.getExpressCategoryId()) &&
                                (expressEnterprise.get().length() + orderProductVO.getExpressCategoryId().length()) <= 100
                        ) {
                            HTExpressCategory category = expressCategoryService.getById(orderProductVO.getExpressCategoryId());
                            if (oConvertUtils.isNotEmpty(category) && !expressEnterprise.get().contains(category.getName())) {
                                expressEnterprise.set(expressEnterprise.get() + " " + category.getName());
                            }
                            if (oConvertUtils.isNotEmpty(category) && !expressSearchUrl.get().contains(category.getSearchUrl())) {
                                expressSearchUrl.set(expressSearchUrl.get() + " " + category.getSearchUrl());
                            }
                        }

                        if (oConvertUtils.isNotEmpty(orderProductVO.getExpressSn()) &&
                                !expressSn.get().contains(orderProductVO.getExpressSn()) &&
                                (expressSn.get().length() + orderProductVO.getExpressSn().length()) <= 1000
                        ) {
                            expressSn.set(expressSn.get() + " " + orderProductVO.getExpressSn());
                        }

                        orderProductItems.add(orderProductVO);
                    }
                    orderShopVO.setOrderProductItems(orderProductItems);
                }
                orderVO.setExpressEnterprise(expressEnterprise.get());
                orderVO.setExpressSearchUrl(expressSearchUrl.get());
                orderVO.setExpressSn(expressSn.get());
                orderVO.setOrderShop(orderShopVO);
            }
        });
    }

    private void handleOrderVOForOrderedLibraryBy(HTOrderVO orderVO, HTOrder order) {
        HTAddressVO address = buyerAddressService.queryByAddressId(order.getAddressId());
        orderVO.setAddress(address);

        //查询子订单商品集合
        List<HTOrderLibrary> orderLibraryList = orderLibraryService.findAllByOrderId(order.getId());
        //按shopID聚合
        AtomicReference<HTOrderShopVO> orderShopVO = new AtomicReference<>();
        Map<String, List<HTOrderLibrary>> collect =
                orderLibraryList.stream().collect(Collectors.groupingBy(HTOrderLibrary::getShopId));
        collect.forEach((shopId, groupedOrderGoodsList) -> {
            HTOrderShop orderShop = orderShopService.queryByOrderId(order.getId());
            orderShopVO.set(SmartBeanUtil.copy(orderShop, HTOrderShopVO.class));

            if (oConvertUtils.isNotEmpty(groupedOrderGoodsList)) {
                //按店铺构建订单商品信息项
                List<HTOrderProductVO> orderProductItems = new ArrayList<>();
                for (HTOrderLibrary orderLibrary : groupedOrderGoodsList) {
                    HTOrderProductVO orderLibraryVO = SmartBeanUtil.copy(orderLibrary, HTOrderProductVO.class);
                    orderProductItems.add(orderLibraryVO);
                }
                orderShopVO.get().setOrderProductItems(orderProductItems);
            }
        });

        orderVO.setOrderShop(orderShopVO.get());
    }

    private void handleOrderVOForOrderedReportBy(HTOrderVO orderVO, HTOrder order) {
        HTAddressVO address = buyerAddressService.queryByAddressId(order.getAddressId());
        orderVO.setAddress(address);

        //查询子订单商品集合
        List<HTOrderReport> orderReportList = orderReportService.findAllByOrderId(order.getId());
        //按shopID聚合
        AtomicReference<HTOrderShopVO> orderShopVO = new AtomicReference<>();
        Map<String, List<HTOrderReport>> collect =
                orderReportList.stream().collect(Collectors.groupingBy(HTOrderReport::getShopId));
        collect.forEach((shopId, groupedOrderGoodsList) -> {
            HTOrderShop orderShop = orderShopService.queryByOrderId(order.getId());
            orderShopVO.set(SmartBeanUtil.copy(orderShop, HTOrderShopVO.class));

            if (oConvertUtils.isNotEmpty(groupedOrderGoodsList)) {
                //按店铺构建订单商品信息项
                List<HTOrderProductVO> orderProductItems = new ArrayList<>();
                for (HTOrderReport orderReport : groupedOrderGoodsList) {
                    HTOrderProductVO orderReportVO = SmartBeanUtil.copy(orderReport, HTOrderProductVO.class);
                    orderProductItems.add(orderReportVO);
                }
                orderShopVO.get().setOrderProductItems(orderProductItems);
            }
        });

        orderVO.setOrderShop(orderShopVO.get());
    }

    /*
     * 获取订单信息通过不同方式
     *
     */
    @Override
    public HTOrderVO getOrderInfoByOrderInfoType(HTOrderInfoBO bo) {
        List<HTOrderProductVO> orderProductVOList = null;
        HTOrderInfoTypeEnum orderInfoType = bo.getOrderInfoType();
        HTOrderVO orderVO = null;
        switch (orderInfoType) {
            case CONFIRM_FROM_GOODS: {
                orderProductVOList = getOrderProductVOListForPurchaseImmediatelyGoods(bo.getGoodsId(), bo.getQuantity());
                orderVO = getShopOrderVOAndUpdateOrderProductVO(orderProductVOList);
            }
            break;

            case CONFIRM_FROM_LIBRARY: {
                orderProductVOList = getOrderProductVOListForPurchaseImmediatelyLibrary(bo.getLibraryId(), bo.getQuantity());
                orderVO = getShopOrderVOAndUpdateOrderProductVO(orderProductVOList);
            }
            break;

            case CONFIRM_FROM_REPORT: {
                orderProductVOList = getOrderProductVOListForPurchaseImmediatelyReport(bo.getReportId(), bo.getQuantity());
                orderVO = getShopOrderVOAndUpdateOrderProductVO(orderProductVOList);
            }
            break;

            case CONFIRM_FROM_CART:
            case CART_INFO: {
                orderProductVOList = getOrderProductVOListFromCart(bo.getBuyerId(), orderInfoType);
                orderVO = getShopOrderVOAndUpdateOrderProductVO(orderProductVOList);
            }
            break;

            case ORDERED: {
                HTOrder order = getById(bo.getOrderId());
                orderVO = SmartBeanUtil.copy(order, HTOrderVO.class);

                HTPayment payment = paymentService.getById(order.getPaymentId());
                HTPaymentVO paymentVO = SmartBeanUtil.copy(payment, HTPaymentVO.class);
                orderVO.setPayment(paymentVO);

                HTOrderTypeEnum orderType = HTOrderTypeEnum.values()[order.getOrderType()];
                switch (orderType) {
                    case GOODS: {
                        handleOrderVOForOrderedGoodsBy(orderVO, order);
                    }
                    break;

                    case LIBRARY: {
                        handleOrderVOForOrderedLibraryBy(orderVO, order);
                    }
                    break;

                    case REPORT: {
                        handleOrderVOForOrderedReportBy(orderVO, order);
                    }
                    break;

                    case INDUSTRY_MEETING: {
                        HTOrderMeeting orderMeeting = orderMeetingService.queryByOrderId(orderVO.getId());
                        HTOrderIndustryVO orderIndustryVO = SmartBeanUtil.copy(orderMeeting, HTOrderIndustryVO.class);
                        orderVO.setOrderIndustry(orderIndustryVO);
                    }
                    break;

                    case INDUSTRY_EXHIBITION: {
                        HTOrderExhibition orderExhibition = orderExhibitionService.queryByOrderId(orderVO.getId());
                        HTOrderIndustryVO orderIndustryVO = SmartBeanUtil.copy(orderExhibition, HTOrderIndustryVO.class);
                        orderVO.setOrderIndustry(orderIndustryVO);
                    }
                    break;

                    case INDUSTRY_SALON: {
                        HTOrderSalon orderSalon = orderSalonService.queryByOrderId(orderVO.getId());
                        HTOrderIndustryVO orderIndustryVO = SmartBeanUtil.copy(orderSalon, HTOrderIndustryVO.class);
                        orderVO.setOrderIndustry(orderIndustryVO);
                    }
                    break;

                    default:
                        break;
                }

            }
            break;

            default:
                break;
        }

        return orderVO;
    }

    @Override
    public List<HTOrder> findAllByParentId(String parentId) {
        return baseMapper.findAllByParentId(parentId);
    }

    /*
     * 如果有必要（结算来自购物车），则删除购物车项目
     *
     */
    private boolean removeCartItemIfNeed(HTSubmitOrderBO bo, List<HTOrderProductVO> orderProductVOList) {
        if (bo.getOrderInfoType() == CONFIRM_FROM_CART) {
            AtomicBoolean success = new AtomicBoolean(false);
            orderProductVOList.forEach((orderProductVO) -> {
                success.set(cartService.removeById(orderProductVO.getCartId()));
            });
            return success.get();
        }
        return true;
    }

    /*
     * 通过ShopID获取对应店铺留言
     *
     */
    private String getShopLeaveMessage(List<HashMap<String, String>> leaveMessages, String shopId) {
        String leaveMessage = null;
        List<HashMap<String, String>> shopLeaveMessage = leaveMessages.stream().filter(map -> oConvertUtils.isNotEmpty(map.get("shopId")) && map.get("shopId").equals(shopId)).collect(Collectors.toList());
        if (!shopLeaveMessage.isEmpty()) {
            HashMap<String, String> messageMap = shopLeaveMessage.get(0);
            if (oConvertUtils.isNotEmpty(messageMap.get("leaveMessage"))) {
                leaveMessage = messageMap.get("leaveMessage");
            }
        }
        return leaveMessage;
    }

    /*
     * 保存订单店铺项
     *
     */
    private void saveOrderShopItems(HTSubmitOrderBO bo, HTOrder order, HTOrderVO orderVO) {
        for (HTOrderShopVO orderShopVO : orderVO.getOrderShopItems()) {
            HTOrderShop orderShop = SmartBeanUtil.copy(orderShopVO, HTOrderShop.class);
            orderShop.setOrderId(order.getId());
            String leaveMessage = getShopLeaveMessage(bo.getLeaveMessages(), orderShop.getShopId());
            if (oConvertUtils.isNotEmpty(leaveMessage)) {
                orderShop.setLeaveMessage(leaveMessage);
            }
            try {
                orderShopService.save(orderShop);
            } catch (Exception e) {
                throw new JeecgBootException("保存订单店铺信息失败");
            }
        }
    }

    /*
     * 保存订单信息
     *
     */
    private void saveOrderProductItems(HTOrder order, List<HTOrderProductVO> orderProductVOList, HTSubmitOrderBO bo) {
        Map<String, List<HTOrderProductVO>> collect = orderProductVOList.stream().collect(Collectors.groupingBy(HTOrderProductVO::getShopId));
        collect.forEach((shopId, groupedOrderGoodsList) -> {
            if (oConvertUtils.isNotEmpty(groupedOrderGoodsList)) {
                HTMerchant shop = ihtMerchantService.getById(shopId);
                if (oConvertUtils.isNotEmpty(shop)) {
                    for (HTOrderProductVO orderProductVO : groupedOrderGoodsList) {
                        if (oConvertUtils.isNotEmpty(orderProductVO.getGoodsId())) {
                            // 商品
                            HTOrderGoods orderGoodsItem = SmartBeanUtil.copy(orderProductVO, HTOrderGoods.class);
                            orderGoodsItem.setBuyerId(bo.getBuyerId());
                            orderGoodsItem.setShopId(shop.getId());
                            orderGoodsItem.setShopName(shop.getEnterpriseName());
                            orderGoodsItem.setOrderId(order.getId());
                            orderGoodsItem.setOrderStatus(WAITING_USER_PAY.getValue());
                            try {
                                orderGoodsService.save(orderGoodsItem);
                            } catch (Exception e) {
                                throw new JeecgBootException("保存订单产品信息失败");
                            }
                        } else if (oConvertUtils.isNotEmpty(orderProductVO.getLibraryId())) {
                            // 资料
                            // 如果libraryId不为空
                            String libraryId = orderProductVO.getLibraryId();
                            String buyerId = bo.getBuyerId();
                            HTOrderLibrary orderedOrderLibrary = orderLibraryService.findBy(buyerId, libraryId);
                            if (oConvertUtils.isEmpty(orderedOrderLibrary)) {
                                HTOrderLibrary orderLibrary = SmartBeanUtil.copy(orderProductVO, HTOrderLibrary.class);
                                orderLibrary.setBuyerId(bo.getBuyerId());
                                orderLibrary.setShopId(shop.getId());
                                orderLibrary.setShopName(shop.getEnterpriseName());
                                orderLibrary.setOrderId(order.getId());
                                orderLibrary.setOrderStatus(WAITING_USER_PAY.getValue());
                                if (oConvertUtils.isEmpty(bo.getReceivedArchivesEmail())) {
                                    throw new JeecgBootException("接收资料的邮箱不能为空");
                                }
                                orderLibrary.setReceivedArchivesEmail(bo.getReceivedArchivesEmail());
                                try {
                                    checkLibrary(orderLibrary);
                                    orderLibraryService.save(orderLibrary);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new JeecgBootException(e.getMessage());
                                }
                            } else {
                                throw new JeecgBootException("已购买该资料");
                            }
                        } else if (oConvertUtils.isNotEmpty(orderProductVO.getReportId())) {
                            // 报告
                            // 如果reportId不为空
                            String reportId = orderProductVO.getReportId();
                            String buyerId = bo.getBuyerId();
                            HTOrderReport orderedOrderReport = orderReportService.findBy(buyerId, reportId);
                            if (oConvertUtils.isEmpty(orderedOrderReport)) {
                                HTOrderReport orderReport = SmartBeanUtil.copy(orderProductVO, HTOrderReport.class);
                                orderReport.setBuyerId(bo.getBuyerId());
                                orderReport.setShopId(shop.getId());
                                orderReport.setShopName(shop.getEnterpriseName());
                                orderReport.setOrderId(order.getId());
                                orderReport.setOrderStatus(WAITING_USER_PAY.getValue());
                                if (oConvertUtils.isEmpty(bo.getReceivedArchivesEmail())) {
                                    throw new JeecgBootException("接收报告的邮箱不能为空");
                                }
                                orderReport.setReceivedArchivesEmail(bo.getReceivedArchivesEmail());
                                try {
                                    checkReport(orderReport);
                                    orderReportService.save(orderReport);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new JeecgBootException(e.getMessage());
                                }
                            } else {
                                throw new JeecgBootException("已购买该报告");
                            }
                        }
                    }
                } else {
                    throw new JeecgBootException("商品店铺实体不能为空");
                }

            }
        });
    }

    private void checkLibrary(HTOrderLibrary orderedOrderLibrary) {

        if (oConvertUtils.isEmpty(orderedOrderLibrary.getArchiveUrl())) {
            throw new JeecgBootException("当前资料无资料文件");
        }
        if (oConvertUtils.isEmpty(orderedOrderLibrary.getPreviewArchiveUrl())) {
            throw new JeecgBootException("当前资料无预览文件");
        }
    }
    private void checkReport(HTOrderReport orderReport) {

        if (oConvertUtils.isEmpty(orderReport.getArchiveUrl())) {
            throw new JeecgBootException("当前资料无资料文件");
        }
        if (oConvertUtils.isEmpty(orderReport.getPreviewArchiveUrl())) {
            throw new JeecgBootException("当前资料无预览文件");
        }
    }

    private String createOrderSn() {
        return DateUtil.format(new Date(), "yyyyMMddHHmmssSSS");
    }

    private HTOrder createOrder(HTOrderTypeEnum orderType,
                                String buyerId,
                                String addressId,
                                BigDecimal totalAmount,
                                BigDecimal totalDiscountAmount,
                                BigDecimal totalPaymentAmount) {
        HTOrder order = new HTOrder();

        order.setOrderType(orderType.getValue());
        order.setOrderSn(createOrderSn());
        order.setBuyerId(buyerId);
        order.setAddressId(addressId);
        order.setCreateTime(new Date());
        order.setTotalAmount(totalAmount);
        order.setTotalDiscountAmount(totalDiscountAmount);
        order.setTotalPaymentAmount(totalPaymentAmount);
        order.setOrderStatus(WAITING_USER_PAY.getValue());

        return order;
    }

    private HTPayment createPayment(HTOrder order, Integer paymentType, BigDecimal amount, String paymentDescription) {
        assert order != null;

        String paySn = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS");
        HTPayment paymentItem = new HTPayment();
        if (oConvertUtils.isNotEmpty(order.getBuyerId())) {
            String buyerId = order.getBuyerId();
            HTTencentAccount tencentAccount = tencentAccountService.queryByUserId(buyerId);
            if (oConvertUtils.isNotEmpty(tencentAccount) && oConvertUtils.isNotEmpty(tencentAccount.getOfficialAccountOpenId())) {
                paymentItem.setPayerId(tencentAccount.getOfficialAccountOpenId());
            }
        }

        paymentItem.setOrderId(order.getId());
        paymentItem.setOutTradeNo(order.getOrderSn());
        paymentItem.setPaymentType(paymentType);
        paymentItem.setPaymentSn(paySn);
        paymentItem.setAmount(amount);
        paymentItem.setPaymentStatus(WAITING_PAYMENT.getValue());
        paymentItem.setPaymentDescription(paymentDescription);
        paymentItem.setPlatformMerchantName("收银台：长沙新材料产业研究院");

        return paymentItem;
    }

    /*
     * 获取订单商品信息列表为购物车
     *
     */
    @NotNull
    private List<HTOrderProductVO> getOrderProductVOListFromCart(String buyerId, HTOrderInfoTypeEnum orderInfoType) {
        List<HTOrderProductVO> orderProductVOList = new ArrayList<>();
        LambdaQueryWrapper<HTCart> cartQueryWrapper = new LambdaQueryWrapper<>();
        cartQueryWrapper.eq(HTCart::getBuyerId, buyerId);

        //1 购物车Item列表
        List<HTCart> list = cartService.list(cartQueryWrapper);

        //2 转换数据模型 HTCart -> HTOrderGoodsVO
        for (HTCart cart : list) {
            boolean requireAddToList = true;
            switch (orderInfoType) {
                case CONFIRM_FROM_CART:
                    requireAddToList = cart.getChecked();
                    break;
                default:
                    break;
            }
            if (requireAddToList) {
                HTOrderProductVO orderProductVO = null;
                if (oConvertUtils.isNotEmpty(cart.getGoodsId())) {
                    HTGoods goods = goodsService.getById(cart.getGoodsId());
                    orderProductVO = SmartBeanUtil.copy(goods, HTOrderProductVO.class);
                    orderProductVO.setGoodsId(goods.getId());
                } else if (oConvertUtils.isNotEmpty(cart.getLibraryId())) {
                    HTLibrary library = libraryService.getById(cart.getLibraryId());
                    orderProductVO = SmartBeanUtil.copy(library, HTOrderProductVO.class);
                    orderProductVO.setLibraryId(library.getId());
                } else if (oConvertUtils.isNotEmpty(cart.getReportId())) {
                    HTReport report = reportService.getById(cart.getReportId());
                    orderProductVO = SmartBeanUtil.copy(report, HTOrderProductVO.class);
                    orderProductVO.setReportId(report.getId());
                } else {
                    orderProductVO = SmartBeanUtil.copy(cart, HTOrderProductVO.class);
                }
                orderProductVO.setCartId(cart.getId());
                orderProductVO.setBuyerId(cart.getBuyerId());
                orderProductVO.setQuantity(cart.getQuantity());
                orderProductVO.setChecked(cart.getChecked());
                orderProductVO.setSubtotalAmount(cart.getSubtotalAmount());
                orderProductVOList.add(orderProductVO);
            }
        }
        return orderProductVOList;
    }

    /*
     * 获取订单商品信息列表为订单提交
     *
     */
    private List<HTOrderProductVO> getOrderProductVOListForSubmit(@NotNull HTSubmitOrderBO bo) {
        HTOrderInfoTypeEnum orderInfoType = bo.getOrderInfoType();
        List<HTOrderProductVO> orderProductVOList = null;
        switch (orderInfoType) {
            case CONFIRM_FROM_GOODS:
                orderProductVOList = getOrderProductVOListForPurchaseImmediatelyGoods(bo.getGoodsId(), bo.getQuantity());
                break;
            case CONFIRM_FROM_LIBRARY:
                orderProductVOList = getOrderProductVOListForPurchaseImmediatelyLibrary(bo.getLibraryId(), bo.getQuantity());
                break;
            case CONFIRM_FROM_REPORT:
                orderProductVOList = getOrderProductVOListForPurchaseImmediatelyReport(bo.getReportId(), bo.getQuantity());
                break;
            case CONFIRM_FROM_CART:
            case CART_INFO:
                orderProductVOList = getOrderProductVOListFromCart(bo.getBuyerId(), orderInfoType);
                break;
            default:
                break;
        }
        return orderProductVOList;
    }

    /*
     * 为立即购买获取订单商品信息列表
     *
     */
    private List<HTOrderProductVO> getOrderProductVOListForPurchaseImmediatelyGoods(String goodsId, int quantity) {
        List<HTOrderProductVO> orderProductVOList = new ArrayList<>();
        HTGoods goodsItem = goodsService.getById(goodsId);
        HTOrderProductVO orderProductVO = SmartBeanUtil.copy(goodsItem, HTOrderProductVO.class);
        orderProductVO.setOrderType(GOODS);
        orderProductVO.setGoodsId(goodsItem.getId());
        orderProductVO.setQuantity(quantity);

        orderProductVOList.add(orderProductVO);
        return orderProductVOList;
    }

    /*
     * 为立即购买获取订单商品信息列表
     *
     */
    private List<HTOrderProductVO> getOrderProductVOListForPurchaseImmediatelyLibrary(String libraryId, int quantity) {
        List<HTOrderProductVO> orderProductVOList = new ArrayList<>();
        HTLibrary libraryItem = libraryService.getById(libraryId);
        HTOrderProductVO orderProductVO = SmartBeanUtil.copy(libraryItem, HTOrderProductVO.class);
        orderProductVO.setOrderType(LIBRARY);
        orderProductVO.setLibraryId(libraryItem.getId());
        orderProductVO.setQuantity(quantity);
        orderProductVOList.add(orderProductVO);
        return orderProductVOList;
    }

    private List<HTOrderProductVO> getOrderProductVOListForPurchaseImmediatelyReport(String reportId, int quantity) {
        List<HTOrderProductVO> orderProductVOList = new ArrayList<>();
        HTReport reportItem = reportService.getById(reportId);
        HTOrderProductVO orderProductVO = SmartBeanUtil.copy(reportItem, HTOrderProductVO.class);
        orderProductVO.setOrderType(REPORT);
        orderProductVO.setReportId(reportItem.getId());
        orderProductVO.setQuantity(quantity);
        orderProductVOList.add(orderProductVO);
        return orderProductVOList;
    }


    private HTOrderShopVO createOrderShopVOByShopId(String shopId) {
        //1 查找店铺实体
        HTShop shop = shopService.getById(shopId);

        //2 构建店铺订单项目VO对象
        HTOrderShopVO orderShopVO = new HTOrderShopVO();
        if (oConvertUtils.isNotEmpty(shop)) {
            orderShopVO.setShopId(shop.getId());
            orderShopVO.setShopName(shop.getName());
        }
        return orderShopVO;
    }

    /*
     * 按店铺归组且更新订单产品信息
     *
     */
    private HTOrderVO getShopOrderVOAndUpdateOrderProductVO(List<HTOrderProductVO> orderProductVOList) {
        HTOrderVO orderVO = new HTOrderVO();
        List<HTOrderShopVO> orderShopVOList = new ArrayList<>();
        try {
            AtomicReference<String> paymentDescription = new AtomicReference<>("");
            Map<String, List<HTOrderProductVO>> collect = orderProductVOList.stream().collect(Collectors.groupingBy(HTOrderProductVO::getShopId));
            AtomicInteger totalQuantity = new AtomicInteger();
            AtomicReference<Double> totalAmount = new AtomicReference<Double>(0.0);
            AtomicReference<Double> totalPaymentAmount = new AtomicReference<>(0.0);

            collect.forEach((shopId, groupedOrderGoodsList) -> {
                HTOrderShopVO orderShopVO = createOrderShopVOByShopId(shopId);

                int shopSubtotalQuantity = 0; //商品种类数量,按店铺
                double shopSubTotalAmount = 0.0;//按店铺小计
                double shopSubTotalPaymentAmount = 0.0;//按店铺小计

                if (groupedOrderGoodsList != null) {
                    //按店铺构建订单商品信息项
                    List<HTOrderProductVO> orderProductItems = new ArrayList<>();
                    for (HTOrderProductVO orderProductVO : groupedOrderGoodsList) {
                        updateOrderProductVOForPreviewOrderBeforeOrdered(orderProductVO);
                        orderProductItems.add(orderProductVO);
                        if (oConvertUtils.isNotEmpty(orderProductVO.getProductName())
                                && !paymentDescription.get().contains(orderProductVO.getProductName()) &&
                                (paymentDescription.get().length() + orderProductVO.getProductName().length()) <= 1000) {
                            paymentDescription.set(paymentDescription.get() + " " + orderProductVO.getProductName());
                        }

                        shopSubtotalQuantity += orderProductVO.getQuantity();
                        shopSubTotalAmount += orderProductVO.getSubtotalAmount().doubleValue();
                        shopSubTotalPaymentAmount += orderProductVO.getSubtotalAmount().doubleValue();
                    }

                    orderShopVO.setSubtotalQuantity(shopSubtotalQuantity);
                    orderShopVO.setSubtotalAmount(BigDecimal.valueOf(shopSubTotalAmount));
                    orderShopVO.setSubtotalPaymentAmount(BigDecimal.valueOf(shopSubTotalPaymentAmount));
                    orderShopVO.setOrderProductItems(orderProductItems);

                    orderShopVOList.add(orderShopVO);

                    double finalStoreSubTotalAmount = shopSubTotalAmount;
                    double finalStoreSubTotalPaymentAmount = shopSubTotalPaymentAmount;
                    totalQuantity.addAndGet(shopSubtotalQuantity);
                    totalAmount.updateAndGet(v -> (double) (v + finalStoreSubTotalAmount));
                    totalPaymentAmount.updateAndGet(v -> (double) (v + finalStoreSubTotalPaymentAmount));
                }
            });
            // System.out.printf("\n\n\n totalAmount %s \n\n\n", JSONObject.toJSONString(totalAmount.get()));
            orderVO.setPaymentDescription(paymentDescription.get());
            orderVO.setTotalQuantity(totalQuantity.get());
            orderVO.setTotalAmount(BigDecimal.valueOf(totalAmount.get()));
            orderVO.setTotalPaymentAmount(BigDecimal.valueOf(totalPaymentAmount.get()));
            orderVO.setOrderShopItems(orderShopVOList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderVO;
    }

    /**
     * 通过GoodsItem, 更新OrderGoodsVO
     */
    private void updateOrderProductVOForPreviewOrderBeforeOrdered(HTOrderProductVO orderProductVO) {
        if (oConvertUtils.isNotEmpty(orderProductVO.getGoodsId())) {
            HTGoods goods = goodsService.getById(orderProductVO.getGoodsId());
            if (oConvertUtils.isNotEmpty(goods)) {
                BigDecimal subtotalAmount = HTCartHelper.calculateSubtotalAmount(goods.getRetailPrice(), orderProductVO.getQuantity());

                orderProductVO.setCover(goods.getCover());
                orderProductVO.setGoodsName(goods.getName());
                orderProductVO.setProductName(goods.getName());
                orderProductVO.setRetailPrice(goods.getRetailPrice());
                orderProductVO.setSubtotalAmount(subtotalAmount);
            }
        }

        if (oConvertUtils.isNotEmpty(orderProductVO.getLibraryId())) {
            HTLibrary library = libraryService.getById(orderProductVO.getLibraryId());
            if (oConvertUtils.isNotEmpty(library)) {
                BigDecimal subtotalAmount = HTCartHelper.calculateSubtotalAmount(library.getRetailPrice(), orderProductVO.getQuantity());

                orderProductVO.setCover(library.getCover());
                orderProductVO.setArchiveName(library.getArchiveName());
                orderProductVO.setProductName(library.getArchiveName());
                orderProductVO.setPreviewArchiveUrl(library.getPreviewArchiveUrl());
                orderProductVO.setRetailPrice(library.getRetailPrice());
                orderProductVO.setSubtotalAmount(subtotalAmount);
            }
        }

        if (oConvertUtils.isNotEmpty(orderProductVO.getReportId())) {
            HTReport report = reportService.getById(orderProductVO.getReportId());
            if (oConvertUtils.isNotEmpty(report)) {
                BigDecimal subtotalAmount = HTCartHelper.calculateSubtotalAmount(report.getRetailPrice(), orderProductVO.getQuantity());
                orderProductVO.setCover(report.getCover());
                orderProductVO.setArchiveName(report.getArchiveName());
                orderProductVO.setProductName(report.getArchiveName());
                orderProductVO.setPreviewArchiveUrl(report.getPreviewArchiveUrl());
                orderProductVO.setRetailPrice(report.getRetailPrice());
                orderProductVO.setSubtotalAmount(subtotalAmount);
            }
        }
    }

    private HTOrder createChildOrderBy(HTOrder parentOrder, HTOrderShop orderShop) {
        HTOrder childOrder = SmartBeanUtil.copy(parentOrder, HTOrder.class);
        childOrder.setId(null);
        childOrder.setIsSplitted(false);
        childOrder.setParentId(parentOrder.getId());
        childOrder.setOrderStatus(WAITING_DELIVERY.getValue());
        childOrder.setOrderSn(createOrderSn());
        childOrder.setTotalAmount(orderShop.getSubtotalAmount());
        childOrder.setTotalDiscountAmount(orderShop.getSubtotalDiscountAmount());
        childOrder.setTotalPaymentAmount(orderShop.getSubtotalPaymentAmount());

        return childOrder;
    }

    //1 更新订单支付状态
    private boolean updatePaymentAfterPaySucceed(String transactionId, String payerId, String outTradeNo) {
        HTPayment payment = paymentService.queryByOutTradeNo(outTradeNo);
        // 支付状态：0-未支付， 1-已支付
        payment.setPaymentStatus(PAID.getValue());
        payment.setTransactionId(transactionId);
        payment.setPayerId(payerId);

        return paymentService.updateById(payment);
    }

    private boolean updateOrderGoodsItemAfterPaySucceed(List<HTOrderGoods> orderGoodsList, String orderId) {
        AtomicBoolean succeed = new AtomicBoolean(false);
        orderGoodsList.forEach(orderGoods -> {
            if (oConvertUtils.isNotEmpty(orderId)) {
                orderGoods.setOrderId(orderId);
            }
            orderGoods.setOrderStatus(WAITING_DELIVERY.getValue());
            orderGoodsService.updateById(orderGoods);
            succeed.set(orderGoodsService.updateById(orderGoods));
        });
        return succeed.get();
    }

    private boolean updateOrderLibraryItemAfterPaySucceed(List<HTOrderLibrary> orderLibraryList, String orderId) {
        AtomicBoolean succeed = new AtomicBoolean(false);
        orderLibraryList.forEach(orderLibrary -> {
            if (oConvertUtils.isNotEmpty(orderId)) {
                orderLibrary.setOrderId(orderId);
            }
            orderLibrary.setOrderStatus(WAITING_DELIVERY.getValue());
            orderLibraryService.updateById(orderLibrary);
            succeed.set(orderLibraryService.updateById(orderLibrary));
        });
        return succeed.get();
    }

    @Override
    @Transactional
    public boolean handleOrderBusinessAfterPaySucceed(String transactionId, String payerId, String outTradeNo) {
        AtomicBoolean succeed = new AtomicBoolean(false);
        // 更新订单支付状态
        succeed.set(updatePaymentAfterPaySucceed(transactionId, payerId, outTradeNo));

        //判断是否需要拆单, 获取主订单下所有order shop对象, 多店铺拆单
        HTOrder parentOrder = queryByOrderSn(outTradeNo);
        List<HTOrderShop> orderShopList = orderShopService.findAllByOrderId(parentOrder.getId());
        boolean isSplitted = orderShopList.size() > 1;

        if (isSplitted) {
            orderShopList.forEach(orderShop -> {
                HTOrder childOrder = createChildOrderBy(parentOrder, orderShop);
                childOrder.setOrderStatus(WAITING_DELIVERY.getValue());
                try {
                    succeed.set(save(childOrder));

                    orderShop.setOrderParentId(parentOrder.getId());
                    orderShop.setOrderId(childOrder.getId());
                    succeed.set(orderShopService.updateById(orderShop));

                    HTOrderTypeEnum orderType = HTOrderTypeEnum.values()[parentOrder.getOrderType()];
                    switch (orderType) {
                        case GOODS:
                            //按店铺查找，订单商品集合, 更新订单商品OrderID到子订单OrderID
                            List<HTOrderGoods> orderGoodsList = orderGoodsService.findAllByShopId(orderShop.getShopId());
                            succeed.set(updateOrderGoodsItemAfterPaySucceed(orderGoodsList, childOrder.getId()));
                            break;

                        case LIBRARY:
                            //按店铺查找，订单商品集合, 更新订单商品OrderID到子订单OrderID
                            List<HTOrderLibrary> orderLibraryList = orderLibraryService.findAllByShopId(orderShop.getShopId());
                            succeed.set(updateOrderLibraryItemAfterPaySucceed(orderLibraryList, childOrder.getId()));

                        default:
                            break;
                    }

                } catch (Exception e) {
                    throw new JeecgBootException("拆单保存失败");
                }
            });
        } else {
            // 支付成功后，更新订单商品信息表状态信息
            List<HTOrderGoods> orderGoodsList = orderGoodsService.findAllByOrderId(parentOrder.getId());
            succeed.set(updateOrderGoodsItemAfterPaySucceed(orderGoodsList, null));
        }

        // 支付成功后，更新主订单状态
        parentOrder.setIsSplitted(isSplitted);
        parentOrder.setOrderStatus(WAITING_DELIVERY.getValue());
        updateById(parentOrder);

        return succeed.get();
    }

    @Override
    public boolean handleIndustryOrderAfterPaySucceed(HTOrderTypeEnum orderType, String transactionId, String payerId,
                                                      String outTradeNo) {
        // 更新订单支付状态
        boolean succeed = false;
        succeed = updatePaymentAfterPaySucceed(transactionId, payerId, outTradeNo);

        //更新主订单状态
        HTOrder parentOrder = queryByOrderSn(outTradeNo);
        parentOrder.setOrderStatus(COMPLETED.getValue());
        updateById(parentOrder);

        switch (orderType) {
            case INDUSTRY_MEETING: {
                HTOrderMeeting orderMeeting = orderMeetingService.queryByOrderId(parentOrder.getId());
                orderMeeting.setOrderStatus(COMPLETED.getValue());

                succeed = orderMeetingService.updateById(orderMeeting);
            }
            break;

            case INDUSTRY_EXHIBITION: {
                HTOrderExhibition orderExhibition = orderExhibitionService.queryByOrderId(parentOrder.getId());
                orderExhibition.setOrderStatus(COMPLETED.getValue());

                succeed = orderExhibitionService.updateById(orderExhibition);
            }
            break;

            case INDUSTRY_SALON: {
                HTOrderSalon orderSalon = orderSalonService.queryByOrderId(parentOrder.getId());
                orderSalon.setOrderStatus(COMPLETED.getValue());

                succeed = orderSalonService.updateById(orderSalon);
            }
            break;

            default:
                break;
        }


        return succeed;
    }


    @Override
    @Transactional
    public IPage<HTOrderVO> pageBy(Page<HTOrder> page, QueryWrapper<HTOrder> queryWrapper) {
        //主订单列表（父订单列表）
        IPage<HTOrder> pageList = page(page, queryWrapper);

        IPage<HTOrderVO> orderVOPageList = new Page<>();
        orderVOPageList.setCurrent(page.getCurrent());
        orderVOPageList.setTotal(page.getTotal());
        orderVOPageList.setPages(page.getPages());

        //遍历父订单，根据情况构建订单信息列表
        List<HTOrderVO> parentOrderList = handleParentOrderList(pageList);
        orderVOPageList.setRecords(parentOrderList);

        return orderVOPageList;
    }

    /**
     * 处理父订单
     */
    private List<HTOrderVO> handleParentOrderList(IPage<HTOrder> pageList) {
        List<HTOrder> records = pageList.getRecords();
        List<HTOrderVO> parentOrderList = new ArrayList<>();

        records.forEach(parentOrder -> {
            HTOrderVO parentOrderVO = SmartBeanUtil.copy(parentOrder, HTOrderVO.class);
            parentOrderList.add(parentOrderVO);

            HTAddressVO addressVO = buyerAddressService.queryByAddressId(parentOrder.getAddressId());
            parentOrderVO.setAddress(addressVO);

            HTOrderTypeEnum orderType = HTOrderTypeEnum.values()[parentOrder.getOrderType()];
            switch (orderType) {
                case GOODS:
                case LIBRARY: {
                    // 查询每条主订单下所有子订单,构建子订单集合
                    List<HTOrderVO> childOrderVOList = handleChildOrderList(parentOrder, addressVO);
                    parentOrderVO.setChildOrderItems(childOrderVOList);
                }
                break;

                case REPORT: {
                    // 查询每条主订单下所有子订单,构建子订单集合
                    List<HTOrderVO> childOrderVOList = handleChildOrderList(parentOrder, addressVO);
                    parentOrderVO.setChildOrderItems(childOrderVOList);
                }
                break;

                case INDUSTRY_MEETING: {
                    HTOrderMeeting orderMeeting = orderMeetingService.queryByOrderId(parentOrderVO.getId());
                    HTOrderIndustryVO orderIndustryVO = SmartBeanUtil.copy(orderMeeting, HTOrderIndustryVO.class);
                    parentOrderVO.setOrderIndustry(orderIndustryVO);
                }
                break;

                case INDUSTRY_EXHIBITION: {
                    HTOrderExhibition orderExhibition = orderExhibitionService.queryByOrderId(parentOrderVO.getId());
                    HTOrderIndustryVO orderIndustryVO = SmartBeanUtil.copy(orderExhibition, HTOrderIndustryVO.class);
                    parentOrderVO.setOrderIndustry(orderIndustryVO);
                }
                break;

                case INDUSTRY_SALON: {
                    HTOrderSalon orderSalon = orderSalonService.queryByOrderId(parentOrderVO.getId());
                    HTOrderIndustryVO orderIndustryVO = SmartBeanUtil.copy(orderSalon, HTOrderIndustryVO.class);
                    parentOrderVO.setOrderIndustry(orderIndustryVO);
                }
                break;

                default:
                    break;
            }
        });

        return parentOrderList;
    }

    //查询每条主订单下所有子订单,构建订单集合
    private List<HTOrderVO> handleChildOrderList(HTOrder parentOrder, HTAddressVO addressVO) {
        List<HTOrderVO> childOrderVOList = new ArrayList<>();
        List<HTOrder> childOrderList = new ArrayList<>();
        //被拆分的订单，查询子订单合集
        if (parentOrder.getIsSplitted()) {
            childOrderList = findAllByParentId(parentOrder.getId());
        } else {
            //未拆单的子订单集就是其自身
            childOrderList.add(parentOrder);
        }
        childOrderList.forEach(childOrder -> {

            HTOrderVO childOrderVO = SmartBeanUtil.copy(childOrder, HTOrderVO.class);
            //查询订单商品集合
            HTOrderTypeEnum orderType = HTOrderTypeEnum.values()[parentOrder.getOrderType()];
            System.out.printf("orderType %s \n", JSONObject.toJSONString(orderType));
            switch (orderType) {
                case GOODS: {
                    childOrderVOList.add(childOrderVO);
                    handleOrderVOForOrderedGoodsBy(childOrderVO, childOrder);
                }

                break;

                case LIBRARY: {
                    childOrderVOList.add(childOrderVO);
                    handleOrderVOForOrderedLibraryBy(childOrderVO, childOrder);
                }
                break;

                case REPORT: {
                    childOrderVOList.add(childOrderVO);
                    handleOrderVOForOrderedReportBy(childOrderVO, childOrder);
                }
                break;
            }
        });

        return childOrderVOList;
    }

    @Override
    public HTOrderStatisticsVO getStatistics(String dayTime) {
        return baseMapper.queryStatistics(dayTime);
    }

    @Override
    public List<HTOrderSalesStatisticsVO> getSalesStatistics(String beginTime, String endTime) {
        return baseMapper.querySalesStatistics(beginTime, endTime);
    }
}
